class Solution {//leetcode675——为高尔夫比赛砍树
private:
    int dx[4]={0,0,-1,1};
    int dy[4]={1,-1,0,0};
    bool vis[51][51];
    int bfs(vector<vector<int>>&forest,int bx,int by,int ex,int ey){
        if(bx==ex&&by==ey) return 0;
        memset(vis,0,sizeof(vis));
        queue<pair<int,int>> q;
        q.push({bx,by});
        int step=0;
        while(q.size()){
            int sz=q.size();
            step++;
            while(sz--){
                auto [x1,y1]=q.front();
                q.pop();
                for(int k=0;k<4;k++){
                    int x=x1+dx[k];
                    int y=y1+dy[k];
                    if(x>=0&&x<m&&y>=0&&y<n&&forest[x][y]!=0&&vis[x][y]==false){
                        if(x==ex&&y==ey) return step;
                        q.push({x,y});
                        vis[x][y]=true;
                    }
                }
            }
        }
        return -1;
    }
public:
    int cutOffTree(vector<vector<int>>& forest) {
        m=forest.size(),n=forest[0].size();
        vector<pair<int,int>>Trees;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(forest[i][j]>1) Trees.push_back({i,j});
            }
        }
        sort(Trees.begin(),Trees.end(),[&forest](pair<int,int>&lhs,pair<int,int>&rhs){
            return forest[lhs.first][lhs.second]<forest[rhs.first][rhs.second];
        });
        int bx=0,by=0;
        int ret=0;
        for(int i=0;i<Trees.size();i++){
            int step=bfs(forest,bx,by,Trees[i].first,Trees[i].second);
            if(step==-1) return -1;
            ret+=step;
            bx=Trees[i].first,by=Trees[i].second;
        }
        return ret;
    }
private:
    int m,n;
    int cnt=0;
};